package com.zxy.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.UUID;

/**
 * @author : zhangxuyuan
 * @Project: rocketmqtest
 * @Package com.zxy.controller
 * @date Date : 2021年05月25日 16:46
 */
@Controller
public class IndexController {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @GetMapping("/")
    public String index(Model model)
    {
        model.addAttribute("goods",redisTemplate.opsForValue().get("goods"));
        return "index";
    }


    @GetMapping("/buy")
    public String buy(Model model)
    {
        String goods = redisTemplate.opsForValue().get("goods");
        Integer goodsVlaue = Integer.valueOf(goods);
        if (goodsVlaue > 0)
        {
            goodsVlaue-=1;
            String orderId = UUID.randomUUID().toString();
            // 发送到订单队列
            rocketMQTemplate.convertAndSend("flashsale",orderId);
            Message message = new Message("flashsaledelay",orderId.getBytes());
            org.springframework.messaging.Message springMessage = RocketMQUtil.convertToSpringMessage(message);
            // 发送到延迟订单队列
            rocketMQTemplate.syncSend(message.getTopic(),springMessage,10000,4);
            redisTemplate.opsForValue().set("goods",goodsVlaue.toString());
            model.addAttribute("orderid",orderId);
            return "pay";
        }
        else
        {
            return "finish";
        }
    }

    @GetMapping("/pay")
    public String pay(@RequestParam("orderid")String orderId)
    {
        // 发送到支付队列
        org.springframework.messaging.Message<String> message = MessageBuilder.withPayload(orderId).build();
        rocketMQTemplate.send("pay",message);
        return "payresult";
    }


}
